﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;
using Ionic.Zip;

using Timer = System.Windows.Forms.Timer;
using System.Drawing;

namespace MinecraftBackupAssistant.Forms
{
    public partial class RestoreForm : Form
    {
        private bool formLoaded = false;

        private string savePath;
        private string backupPath;
        private string selectedBackup;

        private bool isZip;
        private bool shouldBackupZip = Properties.Settings.Default.ShouldZip;
        private bool shouldCreateTemporaryBackup = Properties.Settings.Default.ShouldCreateTemporaryBackup;
        private bool isWorldEmpty;

        private List<BackupEntry> files;
        private List<BackupEntry> directories;
        private List<BackupEntry> total;

        private int count;
        private int totalEntriesInDirectory;

        private bool heightMax = true;
        private bool heightImage = false;
        private int heightDifference = 508;

        public Action UpdateForm;

        public RestoreForm()
        {
            InitializeComponent();
        }

        private void RestoreForm_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.BackupPath == "")
            {
                MessageBox.Show("No backup location has been selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }
            if (!Directory.Exists(Properties.Settings.Default.BackupPath))
            {
                MessageBox.Show("The backup location you have selected does not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }
            if (Directory.GetFiles(Properties.Settings.Default.BackupPath).Length == 0 && Directory.GetDirectories(Properties.Settings.Default.BackupPath).Length == 0)
            {
                MessageBox.Show("There are no backups in the backup location.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }

            Utility.PrepareDirectories();
            populateBackupComboBox();
            temporaryBackupCheckBox.Checked = shouldCreateTemporaryBackup;
            extractMapperImages();

            formLoaded = true;
        }


        private void populateBackupComboBox()
        {
            backupComboBox.Items.Clear();
            try
            {
                files = new List<BackupEntry>();
                directories = new List<BackupEntry>();

                foreach (var file in Directory.GetFiles(Properties.Settings.Default.BackupPath))
                {
                    if (Utility.NameRegex.IsMatch(Path.GetFileName(file)))
                        files.Add(new BackupEntry(Path.GetFileNameWithoutExtension(file), new FileInfo(file).CreationTime, true));
                }

                foreach (var dir in Directory.GetDirectories(Properties.Settings.Default.BackupPath))
                {
                    if (Utility.NameRegex.IsMatch(new DirectoryInfo(dir).Name))
                    directories.Add(new BackupEntry(new DirectoryInfo(dir).Name, new DirectoryInfo(dir).CreationTime, false));
                }

                total = new List<BackupEntry>();
                
                total.AddRange(files);
                total.AddRange(directories);

                total.Sort();
                total.Reverse();

                string format = Properties.Settings.Default.SelectedDateTimeFormat;
                
                DateTime createTime;
                for (int i = 0; i < total.Count; i++)
                {
                    if (Utility.NameRegex.IsMatch(total[i].Name))
                    {
                        Match match = Utility.NameRegex.Match(total[i].Name);


                        if (total[i].IsZip)
                            createTime = File.GetCreationTime(Path.Combine(Properties.Settings.Default.BackupPath, total[i].Name + ".zip")).ToLocalTime();
                        else
                            createTime = Directory.GetCreationTime(Path.Combine(Properties.Settings.Default.BackupPath, total[i].Name)).ToLocalTime();


                        string description = match.Groups["Description"].Value;
                        backupComboBox.Items.Add(String.Format("{0}, Date: {1}{2}{3}", match.Groups["World"], match.Groups["Date"], (total[i].IsZip ? " (ZIP) " : "          "), (description.Length != 0 ? "Attached note: " + description : ""))); //createTime
                    }
                }
                if (backupComboBox.Items.Count > 0) backupComboBox.SelectedIndex = 0;

                Utility.AdjustComboBoxWidth(backupComboBox);
            }
            catch (Exception exception)
            {
                this.Invoke(new Action<Exception>(Utility.HandleError), exception);
            }
        }

        private void extractMapperImages()
        {
            if (!Directory.Exists(Utility.TemporaryMapperPath)) Directory.CreateDirectory(Utility.TemporaryMapperPath);
            string tempImagePath;
            string imagePath;

            //Bitmap bm;
            for (int i = 0; i < total.Count; i++)
            {
                tempImagePath = Utility.CombinePath(Utility.TemporaryMapperPath, total[i].Name.Trim() + Utility.MapperExtension);

                if (Utility.NameRegex.IsMatch(total[i].Name))
                {
                    if (files.Exists(new Predicate<BackupEntry>((backup) => backup.Name == total[i].Name)))
                    {
                        using (ZipFile zip = ZipFile.Read(Utility.CombinePath(Properties.Settings.Default.BackupPath, total[i].Name + ".zip")))
                        {
                            ZipEntry ze = zip[total[i].Name + Utility.MapperExtension];
                            if (ze != null)
                                ze.Extract(Utility.TemporaryMapperPath, ExtractExistingFileAction.OverwriteSilently);
                        }
                    }
                    else //non-zip backup
                    {
                        tempImagePath = Utility.CombinePath(Utility.TemporaryMapperPath, total[i].Name.Trim() + Utility.MapperExtension);
                        imagePath = Utility.CombinePath(Properties.Settings.Default.BackupPath, total[i].Name, total[i].Name + Utility.MapperExtension);
                        if (File.Exists(imagePath))
                            new FileInfo(imagePath).CopyTo(tempImagePath, true);
                    }
                }
            }
            selectMapperImage();
        }

        private void selectMapperImage()
        {
            selectMapperImage(total[0].Name);
        }
        private void selectMapperImage(string name)
        {
            if (File.Exists(Utility.CombinePath(Utility.TemporaryMapperPath, name + Utility.MapperExtension)))
            {
                if (this.heightImage)
                {
                    Height += heightDifference;
                    heightMax = true;
                    heightImage = false;
                }

                pictureBox1.Visible = true;
                noPictureLabel.Visible = false;
                pictureBox1.ImageLocation = Utility.CombinePath(Utility.TemporaryMapperPath, name + Utility.MapperExtension);
            }
            else
            {
                if (this.heightMax)
                {
                    Height -= heightDifference;
                    heightMax = false;
                    heightImage = true;
                }

                pictureBox1.Visible = false;
                noPictureLabel.Visible = true;
            }
        }
        private void setRestoreState(bool state)
        {
            backupComboBox.Enabled = state;
            worldTextBox.Enabled = state;

            restoreButton.Visible = state;
            cancelButton.Visible = state;
            deleteButton.Visible = state;
            deleteAllButton.Visible = state;

            temporaryBackupCheckBox.Visible = state;

            progressBar1.Visible = !state;
        }
        private void restoreButton_Click(object sender, EventArgs e)
        {
            setRestoreState(false);
            try
            {
                if (worldTextBox.Text == "")
                {
                    MessageBox.Show("You have not selected a name for the destination folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    setRestoreState(true);
                    return;
                }
                string minecraftFolder = Properties.Settings.Default.MinecraftPortablePath != "" ? Properties.Settings.Default.MinecraftPortablePath : Utility.CombinePath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ".minecraft", "saves");
                backupPath = Properties.Settings.Default.BackupPath + "\\";
                savePath = Utility.CombinePath(minecraftFolder, worldTextBox.Text);

                isWorldEmpty = !Directory.Exists(savePath) || (Directory.GetFiles(savePath, "*.*", SearchOption.AllDirectories).Length == 0 && Directory.GetDirectories(savePath, "*.*", SearchOption.AllDirectories).Length == 0);
                if (!isWorldEmpty && Directory.Exists(Utility.CombinePath(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name)))
                    Utility.DeleteDirectory(Utility.CombinePath(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name));

                if (isWorldEmpty)
                    Directory.CreateDirectory(savePath);
                this.resetProgressBar();

                isZip = files.Exists(new Predicate<BackupEntry>((backup) => backup.Name == total[backupComboBox.SelectedIndex].Name));
                totalEntriesInDirectory = Utility.GetEntriesInDirectory(Utility.CombinePath(backupPath, total[backupComboBox.SelectedIndex].Name)) + 1;

                selectedBackup = total[backupComboBox.SelectedIndex].Name;

                shouldCreateTemporaryBackup = Properties.Settings.Default.ShouldCreateTemporaryBackup;

                if (shouldCreateTemporaryBackup)
                {
                    toolStripStatusLabel1.Text = "Creating Temporary Backup...";
                    
                    if (!isWorldEmpty)
                    {
                        if (!shouldBackupZip)
                        {
                            Thread copyThread = new Thread(() =>
                            {
                                count = 0;
                                DirectoryInfo saveDir = new DirectoryInfo(savePath);
                                string destination = Path.Combine(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name);
                                if (Directory.Exists(destination))
                                {
                                    DialogResult result = MessageBox.Show("Cannot create temporary backup because a folder with the same name already exists. Do you want to delete it, continue without a temporary backup or cancel the restoring process?", "Cannot create temporary backup", MessageBoxButtons.YesNoCancel);
                                    if (result == DialogResult.Yes)
                                    {
                                        Utility.DeleteDirectory(destination);
                                    }
                                    else if (result == DialogResult.No)
                                    {
                                        shouldCreateTemporaryBackup = false;
                                        this.Invoke(new Action(temporaryBackupCompleted));
                                        return;
                                    }
                                    else
                                        return;
                                }
                                int totalEntriesInTemporarybackup = Utility.GetEntriesInDirectory(saveDir) + 1;
                                SimpleFileCopy.CopyDirectoryWithProgress(saveDir, destination, delegate(double percentage)
                                {
                                    int percent = (int)(percentage * 100);
                                    this.Invoke(new Action(() => this.updateProgress(100, percent)));
                                    

                                    if (++count % 49 == 0)
                                    {
                                        toolStripStatusLabel1.Text = String.Format("Creating Temporary Backup... ({0}/{1})", count, totalEntriesInTemporarybackup);
                                        statusStrip1.Update();
                                    }
                                });

                                setTextTimer("Temporary Backup has been created.", null);
                                this.Invoke(new Action(this.temporaryBackupCompleted));


                            });
                            copyThread.Start();
                            return;
                        }
                        else
                        {
                            Thread zipThread = new Thread(() =>
                                {
                                    using (ZipFile zip = new ZipFile())
                                    {
                                        int totalEntriesInTemporaryBackup = Utility.GetEntriesInDirectory(savePath) + 1;
                                        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                                        zip.Comment = Utility.ZipComment;
                                        zip.AddProgress += ((object zipSender, AddProgressEventArgs zipE) =>
                                            {
                                                if (zipE.EventType == ZipProgressEventType.Adding_AfterAddEntry)
                                                {
                                                    this.Invoke(new Action(() =>
                                                        {
                                                            updateProgress(totalEntriesInTemporaryBackup, zipE.EntriesTotal);
                                                            if (zipE.EntriesTotal % 49 == 0)
                                                            {
                                                                toolStripStatusLabel1.Text = String.Format("Creating Temporary ZIP Backup: Preparing files... ({0}/{1})", zipE.EntriesTotal, totalEntriesInTemporaryBackup);
                                                                statusStrip1.Update();
                                                            }
                                                        }));
                                                }
                                            });
                                        zip.AddDirectory(savePath);


                                        zip.SaveProgress += ((object zipSender, SaveProgressEventArgs zipE) =>
                                        {
                                            this.Invoke(new Action(() =>
                                                {
                                                    if (zipE.EventType == ZipProgressEventType.Saving_AfterWriteEntry)
                                                    {

                                                        updateProgress(zipE.EntriesTotal, zipE.EntriesSaved);
                                                        if (zipE.EntriesSaved % 49 == 0)
                                                        {
                                                            toolStripStatusLabel1.Text = String.Format("Creating Temporary ZIP Backup: Writing files... ({0}/{1})", zipE.EntriesSaved, zipE.EntriesTotal);
                                                            statusStrip1.Update();
                                                        }


                                                    }
                                                    else if (zipE.EventType == ZipProgressEventType.Saving_Completed)
                                                    {
                                                        setTextTimer("Temporary ZIP Backup has been created.", null);
                                                    }
                                                }));
                                        });
                                        zip.Save(Path.GetDirectoryName(savePath) + "\\" + "_" + new DirectoryInfo(savePath).Name + ".zip");
                                        if (Directory.Exists(savePath)) Utility.DeleteDirectory(savePath);
                                        Directory.CreateDirectory(savePath);
                                        this.Invoke(new Action(this.resetProgressBar));
                                        temporaryBackupCompleted();
                                    }
                                });
                            zipThread.Start();
                            return;
                        }

                    }
                    temporaryBackupCompleted();
                }
                else
                    temporaryBackupCompleted();
            }
            catch (Exception exception)
            {
                this.Invoke(new Action<Exception>(Utility.HandleError), exception);
            }
        }

        private void temporaryBackupCompleted()
        {
            this.Invoke(new Action(() => 
            {
                if (Directory.Exists(savePath)) Utility.DeleteDirectory(savePath);

                Directory.CreateDirectory(savePath);

                resetProgressBar();

                if (!isZip)
                {
                    count = 0;
                    string saveDirPath = Utility.CombinePath(backupPath, total[backupComboBox.SelectedIndex].Name);
                    Thread copyThread = new Thread(() =>
                    {
                        DirectoryInfo saveDir = new DirectoryInfo(saveDirPath);
                        SimpleFileCopy.CopyDirectoryWithProgress(saveDir, savePath, delegate(double percentage)
                        {
                            int percent = (int)(percentage * 100);
                            this.Invoke(new Action(() =>
                                {
                                    this.updateProgress(100, percent);

                                    if (++count % 49 == 0)
                                    {
                                        toolStripStatusLabel1.Text = String.Format("Copying files from backup... ({0}/{1})", count, totalEntriesInDirectory);
                                        statusStrip1.Update();
                                    }
                                }));
                        });

                        this.Invoke(new Action(() =>
                            {
                                setTextTimer("The backup has been restored.", null);

                                this.copyCompleted();
                            }));
                    });
                    copyThread.Start();
                }
                else
                {
                    string extractPath = backupPath + total[backupComboBox.SelectedIndex].Name + ".zip";
                    Thread zipThread = new Thread(() =>
                        {
                            using (ZipFile extract = ZipFile.Read(extractPath))
                            {
                                extract.ExtractProgress += ((sender, e) =>
                                    {
                                        this.Invoke(new Action(() =>
                                        {
                                            if (e.EventType == ZipProgressEventType.Extracting_AfterExtractEntry)
                                            {
                                                updateProgress(e.EntriesTotal, e.EntriesExtracted);
                                                if (e.EntriesExtracted % 49 == 0)
                                                {
                                                    toolStripStatusLabel1.Text = String.Format("Extracting backup... ({0}/{1})", e.EntriesExtracted, e.EntriesTotal);
                                                    statusStrip1.Update();
                                                }
                                            }
                                            if (e.EventType == ZipProgressEventType.Extracting_AfterExtractAll)
                                            {
                                                updateProgress(e.EntriesTotal, e.EntriesTotal);

                                                setTextTimer("The backup has been extracted.", null);
                                            }
                                        }));
                                    });

                                extract.ExtractAll(savePath, ExtractExistingFileAction.OverwriteSilently);
                                File.Delete(Utility.CombinePath(savePath, selectedBackup + Utility.MapperExtension));
                                this.copyCompleted();
                            }
                        });
                    zipThread.Start();
                }
            }));
        }
    
        private void copyCompleted()
        {
            this.Invoke(new Action(() =>
            {
                progressBar1.Visible = false;
                if (!isWorldEmpty && shouldCreateTemporaryBackup)
                {
                    DialogResult result = MessageBox.Show("Restore of " + Utility.NameRegex.Match(total[backupComboBox.SelectedIndex].Name).Groups[1] + "\nhas been placed into " + worldTextBox.Text + ".\nDo you want to delete the temporary backup (Yes), keep it (No) or reverse the Restore (Cancel)?", "Restore Completed", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.Yes)
                    {
                        if (!shouldBackupZip)
                            Utility.DeleteDirectory(Path.Combine(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name));
                        else
                            File.Delete(Path.Combine(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name + ".zip"));
                        
   
                        MessageBox.Show("The Temporary Backup has been deleted.", "Temporary Backup Deleted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        if (UpdateForm != null)
                            UpdateForm();

                        resetForm();
                    }
                    else if (result == DialogResult.No)
                    {
                        resetForm();

                        if (UpdateForm != null)
                            UpdateForm();
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        progressBar1.Visible = true;
                        this.resetProgressBar();

                        if (Directory.Exists(savePath)) Utility.DeleteDirectory(savePath);

                        Directory.CreateDirectory(savePath);
                        if (!shouldBackupZip)
                        {
                            int count = 0;
                            Thread copyThread = new Thread(delegate() 
                            {
                                string saveDir = Path.Combine(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name);
                                SimpleFileCopy.CopyDirectoryWithProgress(new DirectoryInfo(saveDir), savePath, delegate(double percentage)
                                {
                                    int percent = (int)(percentage * 100);
                                    this.Invoke(new Action(() =>
                                        {
                                            this.updateProgress(100, percent);

                                            if (++count % 49 == 0)
                                            {
                                                toolStripStatusLabel1.Text = String.Format("Copying from Temporary Backup... ({0}/{1})", count, totalEntriesInDirectory);
                                                statusStrip1.Update();
                                            }
                                        }));
                                });

                                this.Invoke(new Action(() =>
                                    {
                                        setTextTimer("The Temporary Backup has been copied.", null);


                                        this.Invoke(new Action(this.reverseCompleted));
                                    }));
                            });
                            copyThread.Start();
                        }
                        else
                        {
                            Thread zipThread = new Thread(() =>
                                {
                                    using (ZipFile extract = ZipFile.Read(Path.GetDirectoryName(savePath) + "\\" + "_" + new DirectoryInfo(savePath).Name + ".zip"))
                                    {
                                        extract.ExtractProgress += ((sender, e) =>
                                            {
                                                this.Invoke(new Action(() =>
                                                    {
                                                        if (e.EventType == ZipProgressEventType.Extracting_AfterExtractEntry)
                                                        {
                                                            updateProgress(e.EntriesTotal, e.EntriesExtracted);
                                                            if (e.EntriesExtracted % 49 == 0)
                                                            {
                                                                toolStripStatusLabel1.Text = String.Format("Reversing the restore: Extracting Temporary Backup... ({0}/{1})", e.EntriesExtracted, e.EntriesTotal);
                                                                statusStrip1.Update();
                                                            }
                                                        }
                                                        else if (e.EventType == ZipProgressEventType.Extracting_AfterExtractAll)
                                                        {
                                                            updateProgress(e.EntriesTotal, e.EntriesTotal);
                                                            setTextTimer("The Temporary Backup has been extracted.", null);
                                                        }
                                                    }));
                                            });

                                        extract.ExtractAll(savePath, ExtractExistingFileAction.OverwriteSilently);
                                    }
                                    this.Invoke(new Action(this.reverseCompleted));
                                });
                            zipThread.Start();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Restore of " + Utility.NameRegex.Match(total[backupComboBox.SelectedIndex].Name).Groups[1] + " has been placed into " + worldTextBox.Text + ".", "Restore Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (UpdateForm != null)
                        UpdateForm();

                    resetForm();
                }
            }));
        }

        private void resetForm()
        {
            RestoreForm_Load(null, null);
            setRestoreState(true);
        }

        private void setTextTimer(string text, int? interval)
        {
            if (!interval.HasValue) interval = 3000;
            toolStripStatusLabel1.Text = text;
            statusStrip1.Update();
            Timer timer = new Timer() { Interval = interval.Value };
            timer.Tick += ((sender, e) =>
            {
                if (toolStripStatusLabel1.Text == text)
                    toolStripStatusLabel1.Text = "";
            });
            timer.Start();
        }


        private void reverseCompleted()
        {
            this.Invoke(new Action(() => 
            {
                if (!shouldBackupZip)
                    Utility.DeleteDirectory(Path.Combine(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name));
                else
                    File.Delete(Path.Combine(Path.GetDirectoryName(savePath), "_" + new DirectoryInfo(savePath).Name + ".zip"));

                MessageBox.Show("The restore to " + worldTextBox.Text + " was reversed.", "Restore Reversed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                resetForm();
            }));
        }

        public void updateProgress(int maximum, int value)
        {
            progressBar1.Maximum = maximum;
            progressBar1.Value = value;
        }
        private void resetProgressBar()
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = 100;
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete this backup? This action is irreversible.", "Delete Backup", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (files.Exists(new Predicate<BackupEntry>((backup) => backup.Name == total[backupComboBox.SelectedIndex].Name))) //is zip
                        File.Delete(Path.Combine(Properties.Settings.Default.BackupPath, total[backupComboBox.SelectedIndex].Name + ".zip"));
                    else
                        
                     Utility.DeleteDirectory(Path.Combine(Properties.Settings.Default.BackupPath, total[backupComboBox.SelectedIndex].Name));

                    MessageBox.Show(Utility.NameRegex.Match(total[backupComboBox.SelectedIndex].Name).Groups[1] + " was deleted.", "Backup Deleted", MessageBoxButtons.OK);

                    total.RemoveAt(backupComboBox.SelectedIndex);
                    backupComboBox.Items.RemoveAt(backupComboBox.SelectedIndex);

                    if (backupComboBox.Items.Count == 0)
                    {
                        MessageBox.Show("There are no backups to restore.", "No Backups To Restore", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.Close();
                        return;
                    }
                    backupComboBox.SelectedIndex = 0;
                }
            }
            catch (Exception exception)
            {
                this.Invoke(new Action<Exception>(Utility.HandleError), exception);
            }
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void RestoreForm_HelpButtonClicked(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            HelpForm form = new HelpForm(HelpTab.Restore);
            form.ShowDialog();
        }

        private void temporaryBackupCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.ShouldCreateTemporaryBackup = ((CheckBox)sender).Checked;
            Properties.Settings.Default.Save();
            shouldCreateTemporaryBackup = ((CheckBox)sender).Checked;
        }

        private void RestoreForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Utility.DeleteDirectory(Utility.TemporaryMapperPath);
			Directory.CreateDirectory(Utility.TemporaryMapperPath);
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image != null && File.Exists(pictureBox1.ImageLocation))
                System.Diagnostics.Process.Start(pictureBox1.ImageLocation);
        }

        private void backupComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.formLoaded) selectMapperImage(total[backupComboBox.SelectedIndex].Name);
        }

        private void deleteAllButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete all of the backups? This action is irreversible.", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    setRestoreState(false);
                    resetProgressBar();
                    progressBar1.Maximum = backupComboBox.Items.Count;
                    for (int i = 0; i < backupComboBox.Items.Count; i++)
                    {
                        if (files.Exists(new Predicate<BackupEntry>((backup) => backup.Name == total[i].Name))) //is zip
                            File.Delete(Path.Combine(Properties.Settings.Default.BackupPath, total[i].Name + ".zip"));
                        else
                            Utility.DeleteDirectory(Path.Combine(Properties.Settings.Default.BackupPath, total[i].Name));

                        progressBar1.Value = i;
                        progressBar1.Refresh();
                    }
                    progressBar1.Visible = false;
                    MessageBox.Show("All of the backups were deleted.", "Delete", MessageBoxButtons.OK);

                    
                    MessageBox.Show("There are no backups to restore.", "No Backups To Restore", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                    return;
                }
            }
            catch (Exception exception)
            {
                this.Invoke(new Action<Exception>(Utility.HandleError), exception);
            }
        }
    }
}